import { app, shell, BrowserWindow, ipcMain, dialog } from 'electron'
import { join,path } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { execFile } from 'child_process'
import icon from '../../resources/icon.png?asset'

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  //获取本地文件夹路径，传递给渲染进程
  ipcMain.on('get-folder-path', (event) => {
    // 打开文件对话框以选择文件夹
    dialog
      .showOpenDialog({ properties: ['openDirectory'] })
      .then((result) => {
        if (result.canceled) {
          event.sender.send('folder-path-selected', null) // 发送 null 表示未选择文件
          return
        }
        const folderPath = result.filePaths[0]
        console.log(folderPath)
        // 将文件夹路径发送回渲染进程
        event.sender.send('folder-path-selected', folderPath)
      })
      .catch((err) => {
        console.log(err)
      })
  })
  // 获取本地文件路径，传递给渲染进程
  ipcMain.on('get-file-path', (event) => {
    // 打开文件对话框以选择文件
    dialog
      .showOpenDialog({
        properties: ['openFile'],
        filters: [{ name: 'Files', extensions: ['pth', 'py', 'csv', 'pt', 'exe'] }]
      }) // 使用 openFile 选项
      .then((result) => {
        if (result.canceled) {
          event.sender.send('file-path-selected', null) // 发送 null 表示未选择文件
          return
        }
        const filePath = result.filePaths[0] // 获取所选文件的路径
        console.log(filePath)
        // 将文件路径发送回渲染进程
        event.sender.send('file-path-selected', filePath)
      })
      .catch((err) => {
        console.log(err) // 处理错误
      })
  })
  //执行exe并传递参数
  ipcMain.on('execute-exe', (event, { filePath, args }) => {
    executeExeFile(filePath, args)
      .then((result) => {
        console.log(result.stdout)
      })
      .catch((error) => {
        console.error(error)
      })
  })
  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

//执行exe文件并传递参数
async function executeExeFile(filePath, args = [], options = {}) {


  // 2. 参数安全处理（过滤控制字符和空值）
  const sanitizedArgs = args
    .filter(arg => arg != null)
    .map(arg => String(arg).replace(/[\x00-\x1F\x7F]/g, ''));

  // 3. 合并默认选项
  const mergedOptions = {
    timeout: 10000,
    maxBuffer: 1024 * 1024, // 1MB
    ...options
  };

  // 4. 执行子进程
  return new Promise((resolve, reject) => {
    const child = execFile(
      filePath,
      sanitizedArgs,
      mergedOptions,
      (error, stdout, stderr) => {
        if (error) {
          // 增强错误对象信息
          error.details = { 
            filePath: filePath,
            args: sanitizedArgs,
            stderr: stderr?.toString() 
          };
          reject(error);
        } else {
          resolve({ 
            stdout: stdout?.toString(), 
            stderr: stderr?.toString() 
          });
        }
      }
    );

    // 事件监听器（统一错误处理）
    const cleanup = () => {
      child.removeAllListeners();
      if (!child.killed) {
        child.kill();
      }
    };

    child.on('error', (err) => {
      cleanup();
      reject(err);
    });

    child.on('timeout', () => {
      cleanup();
      reject(new Error(`Process timeout after ${mergedOptions.timeout}ms`));
    });

    child.on('exit', (code, signal) => {
      if (code !== 0) {
        reject(new Error(`Process exited with code ${code} (signal: ${signal})`));
      }
    });
  });
}